// pages/address/address.js
// 引入正则匹配
var util = require("../../utils/util.js");
Page({
  data: {
    uid: null,
    dataBox: null,
    address_id: '',
    activeIndex: ''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    // 获取用户uid如果不存在那么将跳转到登录界面
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        if (!res.data) {
          wx.showModal({
            content: '请先登录',
            showCancel: false,
            success: function (res) {
              wx.navigateTo({
                url: '../index/index',
              })
            }
          });
        } else {
          //  添加用户默认id
          that.setData({
            uid: res.data.uid
          })
          // 获取所有用户的地址信息
          var thatUID = res.data.uid
        get(thatUID,that)
        }

      },
    })
  },

  // 点击返回上一界面
  submit: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  // 点击设置默认地址
  click: function (e) {
    var that = this;
    var thatUID = this.data.uid
    that.setData({
      activeIndex: e.currentTarget.dataset.index
    })
    wx.request({
      url: "http://1.aiym.applinzi.com/aiyouwai.php",
      data: {
        type: "updateNewUserAddress",
        paras: {
          uid: this.data.uid,
          address_id: e.currentTarget.dataset.addressid
        }
      },
      header: { "content-type": "application/json" },
      success: function (res) {
      get(thatUID,that)
      }
    })
  },

  //点击删除地址
  clear: function (e) {
    var that = this;
    var thatUID =this.data.uid 
    wx.request({
      url: "http://1.aiym.applinzi.com/aiyouwai.php",
      data: {
        type: "deleteUserAddress",
        paras: {
          address_id: e.currentTarget.dataset.addressid,
        }
      },
      header: { "content-type": "application/json" },
      success: function (res) {
        console.log(res)
        // 删除成功后获取参数
       get(thatUID,that)
      }
    })
  },

  // 点击添加收货信息
  addSlet: function () {
   var that = this
   wx.navigateTo({
     url: '../test/test?uid='+that.data.uid,
   })
  },
  onShow:function(){
    var that = this
    var thatUID = this.data.uid;
get(thatUID,that)
  }
})
// 封装获取所有地址函数
function get(thatUID,that) {
  wx.request({
    url: "http://1.aiym.applinzi.com/aiyouwai.php",
    data: {
      type: "getUserAllAddress",
      paras: {
        uid: thatUID
      }
    },
    header: { "content-type": "application/json" },
    success: function (res) {
      console.log(res)
      that.setData({
        dataBox: res.data
      })
    }
  })
}


